package model;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 *
 * @author Dustin
 */
public class SendThread extends Thread {

    private Socket socket;
    private Queue outputQueue;
    private ObjectOutputStream outputStream;

    public SendThread(Socket aSocket, Queue aQueue) {
        socket = aSocket;
        try {
            outputStream = new ObjectOutputStream(socket.getOutputStream());
            outputQueue = aQueue;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            if (!outputQueue.isEmpty()) {
                try {
                    Packet p = (Packet) outputQueue.dequeue();
                    outputStream.writeObject(p);
                    System.out.println(System.currentTimeMillis() + " Sent frame: " + p.getSeq());
                } catch (IOException ex) {
                    disconnect();
                }
            }
        }
    }

    public void disconnect() {
        try {
            outputStream.close();
            socket.close();
            System.exit(0);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
